package com.suse.lhw.hms.shiroserver;

import com.suse.lhw.hms.shiroserver.config.Authorizing;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

/**
 * @ProjectName: health_manage_system
 * @Package: com.suse.lhw.hms.shiroserver
 * @ClassName: AuthenticationTeat
 * @Description: java类作用描述
 * @Author: 李鸿炜
 * @CreateDate: 2021/1/28 11:39
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/1/28 11:39
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class AuthenticationTeat {
    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

    @Before//在方法开始前添加一个用户
    public void addUser() {
        simpleAccountRealm.addAccount("jim", "123123");

    }

    @Test
    public void testAuthentication() {
        //构建securityMananger环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);

        //主题提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager); //设置securityManager的环境
        Subject subject = SecurityUtils.getSubject(); //获取当前的主体

        UsernamePasswordToken token = new UsernamePasswordToken("jim", "123123"); //
        subject.login(token); //登录

        // subject.isAuthenticated()方法返回一个boolean值,用于判断用户是否认证成功
        System.out.println("isAuthenticated:" + subject.isAuthenticated()); // 输出true

        subject.logout(); // 登出

        System.out.println("isAuthenticated:" + subject.isAuthenticated()); // 输出false
    }

    @Test
    public void testForkDBAuthentication() {
        Authorizing myRealm = new Authorizing(); //实现自己的Realm实例

        //构建SercurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(myRealm);

        //主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();//获取当前的主题

        UsernamePasswordToken token = new UsernamePasswordToken("Jim", "123123");
        subject.login(token);

        // subject.isAuthenticated()方法返回一个boolean值,用于判断用户是否认证成功
        System.out.println("isAuthenticated:" + subject.isAuthenticated()); // 输出true
        // 判断subject是否具有admin和user两个角色权限,如没有则会报错
        subject.checkRoles("admin", "user");
//        subject.checkRole("xxx"); // 报错
        // 判断subject是否具有user:add权限
        subject.checkPermission("user:add");
    }
}
